package com.ygqh.baby.controller.admin;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ygqh.baby.ao.Message;
import com.ygqh.baby.model.YgLoginModel;
import com.ygqh.baby.service.AdminUserService;
import com.ygqh.baby.service.impl.DocumentConstant;

@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController<Object, java.lang.Long> {

	@Autowired
	private AdminUserService adminUserService;
	@Autowired
	private DocumentConstant documentConstant;

	@RequestMapping(value="login",method=RequestMethod.GET)
	public String login(HttpServletRequest request) throws Exception {
		
		return "redirect:/pages/login.html";
	}
	
	@RequestMapping(value="login",method=RequestMethod.POST)
	@ResponseBody
	public YgLoginModel loginPost(HttpServletRequest request ,String username,  String password) throws Exception {
		
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		YgLoginModel model = new YgLoginModel("LOGIN_SUCCESS", documentConstant.LOGIN_SUCCESS);
		try {
			subject.login(token);
	        //获取session
	        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
	        HttpSession session = httpServletRequest.getSession();
	        //把用户信息保存到session
	        session.setAttribute("currentUser", subject.getPrincipal());
		} catch (UnknownAccountException e) {
			model = new YgLoginModel("UNKNOWN_ACCOUNT", documentConstant.UNKNOWN_ACCOUNT);
		} catch (IncorrectCredentialsException e) {
			e.printStackTrace();
			model = new YgLoginModel("INCORRECTCREDENTIALS", documentConstant.INCORRECTCREDENTIALS);
		} catch (Exception e) {
			e.printStackTrace();
			model = new YgLoginModel("UNKNOWN_ERROR", documentConstant.UNKNOWN_ERROR);
		}
		subject.isPermitted("create");
	
		return model;
	}
	
	@RequestMapping(value="logout")
	@ResponseBody
	public Message logout(HttpServletRequest request ,String username,  String password) throws Exception {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return SUCCESS_MESSAGE;
	}
	@RequestMapping("create")
	@ResponseBody
	@RequiresPermissions("product:create")//执行queryItems需要"item:query"权限
	public String create() {
		
		return "ok";
	}
}
